//
//  IndexHeaderController.h
//  yigou
//
//  Created by SunChao on 17/1/16.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "IndexViewController.h"
#import "LgViewController.h"
#import "MsgCenterViewController.h"
#import "IndexModel.h"
#import "IndexHeader.h"
#import "ContentListCell.h"
#import "LUHUnderLineButtonView.h"
#import "IndexHeaderController.h"
#import "ShowImageViewController.h"
#import "DetailCommentController.h"
#import "TopicContentModel.h"
#import "ContentCmtModel.h"
#import "contentLikeModel.h"
#import "ArticleWebViewController.h"
#import "TopicleWebViewController.h"
#import "DFLineCellManager.h"
#import "DFBaseLineCell.h"
#import "DFLineLikeItem.h"
#import "DFLineCommentItem.h"
#import "CommentInputView.h"

#import "MMPopupItem.h"
#import "MMSheetView.h"
#import "MMPopupWindow.h"
#import "DFLikeCommentView.h"
//#import "YXCustomActionSheet.h"
#import "DyShare.h"

#import "DFImagePreviewViewController.h"
#import "TribeDetailViewController.h"
#import "CustomWebViewController.h"
#import "PaiGoodListViewController.h"
#import "HisHomePageViewController.h"

#define sectionHeaderHeight (15)
typedef NS_OPTIONS(NSUInteger, SelectType) {
    SelectTypeArticle = 1,//文章
    SelectTypeTopic= 2//话题
};
#define padding 10
@interface IndexViewController () <UITableViewDataSource, UITableViewDelegate,LUHUnderLineButtonViewDelegate,DFLineCellDelegate, CommentInputViewDelegate,UINavigationControllerDelegate, DFImagePreviewViewControllerDelegate, YXCustomActionSheetDelegate,IndexHeaderDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)IndexHeaderController *indexHeaderView;
@property (strong, nonatomic) UILabel *noticecount;
@property (nonatomic,strong)NSMutableDictionary *dataSource;
@property (nonatomic,assign)NSUInteger selectType;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;
@property (nonatomic,strong)LUHUnderLineButtonView *buttonView;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;


@property (strong, nonatomic) CommentInputView *commentInputView;


@property (strong, nonatomic) NSString * currentItemId;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (strong, nonatomic) NSMutableArray *topicHeights;

@end

@implementation IndexViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:POST_LOGINSUC object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    static dispatch_once_t disOnce;
    dispatch_once(&disOnce,  ^ {
        self.indexHeaderView  = [[IndexHeaderController alloc]init];
        self.indexHeaderView.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.tableView.tableHeaderView = self.indexHeaderView.view;
        self.indexHeaderView.dataSource = [NSMutableDictionary new];
        self.indexHeaderView.view.frame = CGRectMake(0, 0, ScreenW, 566);
        [self loadNetworkData];
        self.indexHeaderView.delegate = self;
    });
   
}
-(void)selectedIndexBtn:(NSInteger)button
{
    if (button == 0) {
        _selectType = SelectTypeArticle;
    }else if (button == 1){
        _selectType = SelectTypeTopic;
    }
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageToEnd = NO;
    self.page = 1;
    NSArray *titles = @[@"热门文章",@"热门帖子"];
    self.buttonView = [[LUHUnderLineButtonView alloc]initWithItems:titles];
    self.buttonView.selectedIndex = 0;
    _selectType = SelectTypeArticle;
    self.buttonView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    self.buttonView.delegate = self;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _selectType = SelectTypeArticle;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadHeaderView" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectScorllViewItemAtIndex:) name:@"didSelectScorllViewItemAtIndex" object:nil];
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectedZhiBo) name:@"didSelectedZhiBo" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectedPaiMai) name:@"didSelectedPaiMai" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectedZhongChou) name:@"didSelectedZhongChou" object:nil];
    
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"首页"];
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 20, 20);
    [buttonNotice setBackgroundImage:[UIImage imageNamed:@"topnotice.png"] forState:UIControlStateNormal];
    self.noticecount = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 10, 10)];
    self.noticecount.font = [FontTool fontWithSize:10];
    self.noticecount.textAlignment = NSTextAlignmentCenter;
    self.noticecount.textColor = [UIColor whiteColor];
    self.noticecount.backgroundColor = [UIColor colorWithHexString:@"0EA1B6"];
    self.noticecount.layer.masksToBounds = YES;
    self.noticecount.layer.cornerRadius = 5.f;
    self.noticecount.text = @"1";
    self.noticecount.hidden = YES;
    self.noticecount.userInteractionEnabled = NO;
    [buttonNotice addSubview:self.noticecount];
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;
    [self addRefreshHeader:self.tableView];
    [self addLoadMoreFooter:self.tableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:POST_LOGINSUC object:nil];
   
    [[MMPopupWindow sharedWindow] cacheWindow];
    [MMPopupWindow sharedWindow].touchWildToHide = YES;
    
    MMSheetViewConfig *sheetConfig = [MMSheetViewConfig globalConfig];
    sheetConfig.defaultTextCancel = @"取消";
    
    _items = [NSMutableArray array];
    
    _itemDic = [NSMutableDictionary dictionary];
    
    _commentDic = [NSMutableDictionary dictionary];
    
    [self initCommentInputView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    
    if (![UserData isLogin]) {
        LgViewController *loginViewController = [[LgViewController alloc]initWithNibName:@"LgViewController" bundle:nil];
        [self.navigationController pushViewController:loginViewController animated:NO];
    }
    [self getMsgCount];
    [_commentInputView addNotify];
    
    [_commentInputView addObserver];
    
   
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_commentInputView removeNotify];
    
    [_commentInputView removeObserver];
    
}
//点击消息中心
- (void)clickNotice:(id)sender {
    MsgCenterViewController *vc = [[MsgCenterViewController alloc] initWithNibName:@"MsgCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}
//点击轮播图
- (void)didSelectScorllViewItemAtIndex:(NSNotification *)noti{
    
    NSDictionary *dic = noti.userInfo ;
    NSString *index = [dic objectForKey:@"index"];
    
    CustomWebViewController *vc = [[CustomWebViewController alloc] initWithNibName:@"CustomWebViewController" bundle:nil];
    vc.url = @"";
    [self.navigationController pushViewController:vc animated:YES];
    
}

//点击直播、众筹、拍卖
- (void)didSelectedZhiBo{
    

}
- (void)didSelectedPaiMai{
    PaiGoodListViewController *vc = [[PaiGoodListViewController alloc] initWithNibName:@"PaiGoodListViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didSelectedZhongChou{

    
}

- (void) loginSuccess:(NSNotification *) notify {
    [self loadNetworkData];
}

#pragma mark 消息中心
- (void)getMsgCount {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = INDEXMsgCount;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSInteger count = [[dict objectForKey:@"data"] integerValue];
        if (count == 0) {
            self.noticecount.hidden = YES;
            return ;
        }
        self.noticecount.text = [NSString stringWithFormat:@"%ld", count];
        
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

#pragma mark 轮播图片点击事件
- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;
    NSString *words = @"test share";
    UIImage *shareimg = [UIImage imageNamed:@"placeholder"];
    //NSString *shareUrl = self.myshare.url;
    DyShareType type ;
    
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
            
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        default:
            break;
    }
    if(type&&index!=0) {
        //NSString *strShare = self.myshare.title;
        [[DyShare getInstance]shareWithShareType:type Content:@"" title:@"分享" url:@"https://www.baidu.com" image:shareimg delegate:nil];
    }
}

#pragma mark 热门部落
-(void)didClickHotTribeWithTribeID:(NSString *)tribeID;{
    
    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
    [self.navigationController pushViewController:detail animated:YES];
    detail.tribeID = tribeID;
}

- (void)calculateHeight:(BOOL)append {
    NSInteger i = 0;
//    if (!append) {
//        [self.topicHeights removeAllObjects];
//    } else {
//        i = self.topicHeights.count - 1;
//    }
    [self.topicHeights removeAllObjects];
    for(; i < _items.count; i++) {
        DFBaseLineItem *item = [_items objectAtIndex:i];
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        NSInteger height = [typeCell getReuseableCellHeight:item]+40;
        [self.topicHeights addObject:[NSNumber numberWithInteger:height]];
    }
}

#pragma mark tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    IndexModel *model = [[IndexModel alloc]initWithDictionary:self.dataSource error:nil];
    if (_selectType == SelectTypeArticle) {
        NSLog(@"%@",model.topicList);
        return model.articleList.count;
    }else if (_selectType == SelectTypeTopic){
        return _items.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_selectType == SelectTypeArticle) {
        return 440;
    }else if (_selectType == SelectTypeTopic){
        NSNumber *numh = self.topicHeights[indexPath.row];
        return [numh integerValue];
    }
    
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 10)];
    bottomView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:bottomView];
    [view addSubview:self.buttonView];
    return self.buttonView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IndexModel *model = [[IndexModel alloc]initWithDictionary:self.dataSource  error:nil];
   
    if (_selectType == SelectTypeArticle) {
        ContentListCell *cell = GET_CELL(ContentListCell,@"ContentListCell");
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSArray *array = [NSArray new];
        array = model.articleList;
        NSDictionary *dic = [array objectAtIndex:indexPath.row];
        NSDictionary *tmpDic = [dic objectForKey:@"article"];
        [cell contentWithDic:tmpDic];
        return cell;
        
    }else{
       
        DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
        NSLog(@"----------indexpath:%ld",indexPath.row);
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        
        NSString *reuseIdentifier = NSStringFromClass([typeCell class]);
        DFBaseLineCell *cell = [tableView dequeueReusableCellWithIdentifier: reuseIdentifier];
        if (cell == nil ) {
            cell = [[[typeCell class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }else{
            NSLog(@"重用Cell: %@", reuseIdentifier);
        }
        
        cell.delegate = self;
        
        cell.separatorInset = UIEdgeInsetsZero;
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            cell.layoutMargins = UIEdgeInsetsZero;
        }
        [cell updateWithItem:item];
        
        return cell;
    }
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//
//    IndexModel *model = [[IndexModel alloc]initWithDictionary:self.dataSource error:nil];
//    if (_selectType == SelectTypeArticle) {
//        NSDictionary *dicArticle = [model.articleList objectAtIndex:indexPath.row];
//        NSDictionary *detailArticle = [dicArticle objectForKey:@"article"];
//       NSString *articleContent =  [detailArticle objectForKey:@"content_id"];
//        NSString *articleAuthor =  [detailArticle objectForKey:@"user_id"];
//        NSString *articleTribe =  [detailArticle objectForKey:@"tribe_id"];
//        ArticleWebViewController *articel = [[ArticleWebViewController alloc]initWithNibName:@"ArticleWebViewController" bundle:nil];
//        articel.articleContent = articleContent;
//        articel.articleUserId = articleAuthor;
//        articel.articleTribeId = articleTribe;
//        articel.shareimgurl = [detailArticle objectForKey:@"cover_img"];
//        articel.sharetitle = [detailArticle objectForKey:@"title"];
//        articel.shareurl = [detailArticle objectForKey:@"shareUrl"];
//        [self.navigationController pushViewController:articel animated:YES];
//    }else if (_selectType == SelectTypeTopic){
//
//        return;
//    }
//
//}




#pragma mark 上拉、下拉
- (void)refresh {
    [super refresh];
    [self loadNetworkData];
}

- (void)loadMore {
    [super loadMore];
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = nil;
    self.page +=1;
    if (_selectType == SelectTypeArticle) {
        url = [NSString stringWithFormat:@"%@/sys/index/hotArticle?page=%ld", APIYIGOU, (long)self.page];
    }else if (_selectType == SelectTypeTopic){
        url = [NSString stringWithFormat:@"%@/sys/index/hotTopic?page=%ld", APIYIGOU, (long)self.page];
    }
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *dataArr = [dict objectForKey:@"data"];
        if (dataArr.count == 0) {
            [ViewFactory showSuccess:@"没有更多数据了！"];
            [self.tableView.footer endRefreshing];
            return ;
        }
        if (_selectType == SelectTypeArticle) {
            NSArray *addTopicListArr = dataArr;
            
            
            NSArray *oldTopicListArr = [self.dataSource objectForKey:@"articleList"];
            NSMutableArray *newTopicListArr = [NSMutableArray arrayWithArray:oldTopicListArr];
            [newTopicListArr addObjectsFromArray:addTopicListArr];
            [self.dataSource removeObjectForKey:@"articleList"];
            [self.dataSource setObject:newTopicListArr forKey:@"articleList"];
            
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
        }else if (_selectType == SelectTypeTopic){
            NSArray *addTopicListArr = dataArr;
            [self initDataWithArray:addTopicListArr];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                // 耗时的操作
                [self calculateHeight:YES];
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 更新界面
                    [self.tableView reloadData];
                    [self.tableView.footer endRefreshing];
                });
            });
        }
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

#pragma mark 数据请求
- (void)loadNetworkData {
    [self.dataSource removeAllObjects];
    self.pageToEnd = NO;
    self.page = 1;
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl =  INDEX;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
       
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];

        self.dataSource = [dict objectForKey:@"data"];
        self.indexHeaderView.dataSource = [NSMutableDictionary new];
        self.indexHeaderView.dataSource  = self.dataSource;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadHeaderView" object:nil];
       ;
        [_items removeAllObjects];
        [self initDataWithArray: [self.dataSource objectForKey:@"topicList"]];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 耗时的操作
            [self calculateHeight:NO];
            dispatch_async(dispatch_get_main_queue(), ^{
                // 更新界面
                [self.tableView reloadData];
                [self.tableView.header endRefreshing];
            });  
        });
    } error:^(YTKBaseRequest *request) {
        [self.tableView.header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.header endRefreshing];
    }];
}

- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

//初始化文章数据
-(void) initDataWithArray:(NSArray *)array
{
    
    NSArray *topicArr = array;
    for (NSDictionary *tmpDic in topicArr) {
        NSDictionary *topicDic = [tmpDic objectForKey:@"topic"];
        NSLog(@"dic:%@",topicDic);
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.user_id = [topicDic objectForKey:@"user_id"];
        textImageItem.head_url = [[topicDic objectForKey:@"hyUser"] objectForKey:@"head_url"];
        textImageItem.nick_name = [[topicDic objectForKey:@"hyUser"] objectForKey:@"nick_name"];
        textImageItem.title = [topicDic objectForKey:@"title"];
        textImageItem.content_desc = [topicDic objectForKey:@"content_desc"];
        textImageItem.tribe_name = [topicDic objectForKey:@"tribe_name"];
        textImageItem.publish_tm = [topicDic objectForKey:@"publish_tm"];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.tribe_id = [topicDic objectForKey:@"tribe_id"];
        textImageItem.shareUrl = [topicDic objectForKey:@"shareUrl"];
        textImageItem.cover_img = [topicDic objectForKey:@"cover_img"];
        NSArray *picArr = [topicDic objectForKey:@"mediaList"];
        NSMutableArray *srcImages = [NSMutableArray array];
        for (NSDictionary *tmpDic in picArr) {
            NSString *imgString =  [tmpDic objectForKey:@"media_url"];
            [srcImages addObject:imgString];
        }
        [textImageItem.srcImages removeAllObjects];
        
        textImageItem.srcImages = srcImages;
        
        NSArray *contentCmt = [tmpDic objectForKey:@"contentCmtList"];
        
        for (NSDictionary *cmtDic in contentCmt) {
            NSLog(@"cmtArr:%@",cmtDic);
            DFLineCommentItem *commentItem1_1 = [[DFLineCommentItem alloc] init];
            commentItem1_1.commentId = [cmtDic objectForKey:@"comment_id"];
            commentItem1_1.userId = [cmtDic objectForKey:@"user_id"];
            commentItem1_1.userNick = [cmtDic objectForKey:@"user_nike_name"];
            if (![[cmtDic objectForKey:@"reply_user_id"]isEqualToString:@""]) {
                commentItem1_1.replyUserId = [cmtDic objectForKey:@"reply_user_id"];
                commentItem1_1.replyUserNick = [cmtDic objectForKey:@"reply_user_nike_name"];
            }
            
            commentItem1_1.text = [cmtDic objectForKey:@"comment"];
            
            [textImageItem.comments addObject:commentItem1_1];
        }
        
        NSArray *contentLike = [tmpDic objectForKey:@"contentLikeList"];
        [textImageItem.likes removeAllObjects];
        for (NSDictionary *tmpDic in contentLike) {
            DFLineLikeItem *likeItem1_1 = [[DFLineLikeItem alloc] init];
            likeItem1_1.userId = [tmpDic objectForKey:@"user_id"];
            likeItem1_1.userNick = [tmpDic objectForKey:@"nick_name"];
            likeItem1_1.head_url = [tmpDic objectForKey:@"head_url"];
            [textImageItem.likes addObject:likeItem1_1];
        }
        [self addItem:textImageItem];
    }
    
}

#pragma mark - Method

-(DFBaseLineCell *) getCell:(Class)itemClass
{
    DFLineCellManager *manager = [DFLineCellManager sharedInstance];
    return [manager getCell:itemClass];
}

-(void)addItem:(DFBaseLineItem *)item
{
    [self insertItem:item index:_items.count];
}

-(void) addItemTop:(DFBaseLineItem *) item
{
    [self insertItem:item index:0];
}

-(void) insertItem:(DFBaseLineItem *) item index:(NSUInteger)index
{
    [self genCommentAttrString:item];
    
    [_items insertObject:item atIndex:index];
    
    
    [_itemDic setObject:item forKey:item.content_id];
}

-(DFBaseLineItem *) getItem:(NSString *) itemId
{
    return [_itemDic objectForKey:itemId];
    
}

-(void)addCommentItem:(DFLineCommentItem *)commentItem itemId:(NSString *)itemId replyCommentId:(NSString *)replyCommentId

{
    DFBaseLineItem *item = [self getItem:itemId];
    NSMutableArray *tmpArr = [NSMutableArray new];
    [tmpArr addObject:commentItem];
    [tmpArr addObjectsFromArray:item.comments];
    [item.comments removeAllObjects];
    item.comments = tmpArr;
    [self AddCommentDataRequestWithReplyCommentId:replyCommentId ContentId:itemId CommentText:commentItem.text];
    if (![replyCommentId isEqualToString:@"0"]) {
        DFLineCommentItem *replyCommentItem = [self getCommentItem:replyCommentId];
        
        commentItem.replyUserId = replyCommentItem.userId;
        commentItem.replyUserNick = replyCommentItem.userNick;
       
    }
    
    item.cellHeight = 0;
    [self genCommentAttrString:item];
    [self.tableView reloadData];
    
}

-(void) genCommentAttrString:(DFBaseLineItem *)item
{
    NSMutableArray *comments = item.comments;
    
    [item.commentStrArray removeAllObjects];
    
    for (int i=0; i<comments.count;i++) {
        DFLineCommentItem *comment = [comments objectAtIndex:i];
        [_commentDic setObject:comment forKey:comment.commentId];
        
        NSString *resultStr;
        if (comment.replyUserId == 0) {
            resultStr = [NSString stringWithFormat:@"%@: %@",comment.userNick, comment.text];
        }else{
            resultStr = [NSString stringWithFormat:@"%@回复%@: %@",comment.userNick, comment.replyUserNick, comment.text];
        }
        
        NSMutableAttributedString *commentStr = [[NSMutableAttributedString alloc]initWithString:resultStr];
        if (comment.replyUserId == 0) {
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(0, comment.userNick.length)];
        }else{
            NSUInteger localPos = 0;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(localPos, comment.userNick.length)];
            localPos += comment.userNick.length + 2;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.replyUserId] range:NSMakeRange(localPos, comment.replyUserNick.length)];
        }
        
        NSLog(@"ffff: %@", resultStr);
        
        [item.commentStrArray addObject:commentStr];
    }
}
-(void)onLike:(NSString *)contentId likeItem:(DFLineLikeItem *)likeItem type:(BOOL)type
{
    //点赞
    if (type) {
        
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        [tmpArr addObjectsFromArray:item.likes];
        [item.likes removeAllObjects];
        item.likes = tmpArr;
    }else {
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<item.likes.count; i++) {
           DFLineLikeItem *tmpItem =  [item.likes objectAtIndex:i];
            if ([tmpItem.userId isEqualToString:likeItem.userId]) {
//                NSLog(@"有一样的");
                [array addObject:tmpItem];
            }
        }
        [item.likes removeObjectsInArray:array];
    }
    
    [self.tableView reloadData];
}

-(DFLineCommentItem *)getCommentItem:(NSString *)commentId
{
    return [_commentDic objectForKey:commentId];
}

-(void) initCommentInputView
{
    if (_commentInputView == nil) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _commentInputView.hidden = YES;
        _commentInputView.delegate = self;
        [self.view addSubview:_commentInputView];
    }
    
}
#pragma mark - DFLineCellDelegate

-(void)onComment:(NSString *)itemId
{
    
    _currentItemId = itemId;
    
    _commentInputView.commentId = @"0";
    
    _commentInputView.hidden = NO;
    
    [_commentInputView show];
    [_commentInputView addNotify];
}



//- (void)onClickTitleLabel:(NSString *)tribeId
//{
//    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
//    [self.navigationController pushViewController:detail animated:YES];
//    detail.tribeID = tribeId;
//}

//点击左边头像 或者 点击评论和赞的用户昵称
//-(void)onClickUser:(NSString *)userId
//{
//    NSLog(@"userid:%@",userId);
//    HisHomePageViewController *homepage = [[HisHomePageViewController alloc]init];
//    homepage.userid = userId;
//    [self.navigationController pushViewController:homepage animated:YES];
    
//}
//-(void)onClickHeaderUserAvatar
//{
//    [self onClickUser:@"111"];
//}

-(void)onClickComment:(NSString *)commentId itemId:(NSString *)itemId
{
     _currentItemId = itemId;
    
    _commentInputView.hidden = NO;
    
    _commentInputView.commentId = commentId;
    
    [_commentInputView show];
    
    DFLineCommentItem *comment = [_commentDic objectForKey:commentId];
    [_commentInputView setPlaceHolder:[NSString stringWithFormat:@"  回复: %@", comment.userNick]];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text
{
    [self onCommentCreate:commentId text:text itemId:_currentItemId];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text itemId:(NSString *) itemId
{
    
    DFLineCommentItem *commentItem = [[DFLineCommentItem alloc] init];
    commentItem.commentId = commentId;
    commentItem.userId = [UserData userid];
    commentItem.userNick = [UserData username];
    commentItem.text = text;
    [self addCommentItem:commentItem itemId:itemId replyCommentId:commentId];
}





#pragma mark - UIViewControllerPreviewingDelegate

-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:location];
    
    if(indexPath)
    {
        
        DFBaseLineCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        if (cell && [cell isKindOfClass:[DFTextImageLineCell class]]) {
            DFTextImageLineCell *imageCell = (DFTextImageLineCell *)cell;
//            NSInteger index = [imageCell getIndexFromPoint:location];
            
            DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
            if (item && [item isKindOfClass:[DFTextImageLineItem class]]) {
                DFTextImageLineItem *textItem = (DFTextImageLineItem *) item;
                if (index == -1) {
                    return nil;
                }
                NSString *url  = [textItem.srcImages objectAtIndex:index];
                DFImagePreviewViewController *previewController=[[DFImagePreviewViewController alloc] initWithImageUrl:url itemId:item.content_id];
                previewController.delegate = self;
                previewController.preferredContentSize=CGSizeMake(300, 300);
                return previewController;
            }
        }
    }
    return nil;
}
-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
    [self showViewController:viewControllerToCommit sender:self];
}

ARRAY_INIT(topicHeights)

@end
